package com.neuedu.projectedu.interceptor;

import com.alibaba.fastjson.JSON;
import com.neuedu.projectedu.common.Result;
import com.neuedu.projectedu.utils.JwtUtils;
import com.qcloud.cos.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    @Value("${com.neuedu.secret}")
    private String secret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
//        Map map=new HashMap<>();
//        map.put("message","token不正确，请登录获取");
        Result result=Result.fail("2222","token不正确，请登录获取","无权访问");

        log.info(request.getRequestURI());
        log.info(request.getServletPath());
        log.info(request.getContextPath());
        String token = request.getHeader("token");
        log.info(token);
        if(!StringUtils.isNullOrEmpty(token)) {
            String username = JwtUtils.getUsername(token);
            if (JwtUtils.verify(token, username, secret)) {
                return true;
            }
        }
        response.getWriter().write(JSON.toJSONString(result));
        return false;
    }
}
